package com.market.cash.ui.adapter

import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.recyclerview.widget.RecyclerView
import com.market.cash.R
import com.market.cash.configs.CashRootConfigs
import com.market.cash.utils.adapter.CashRootRecyclerViewAdapter
import com.market.cash.utils.adapter.CashRootViewHolderHelper
import com.market.cash.utils.event.CashRootEventHelper
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.SharedHelper
import com.market.cash.weight.input.CustomEditText
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/22 13:54
 * @Annotation：认证流程步骤适配器
 */
class CashRootStepCommonAdapter(recyclerView: RecyclerView?): CashRootRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//出生日期选择
                return R.layout.cash_step_common_select_item
            }
            "GENDER_PICK" -> {//性别
                return R.layout.cash_step_common_gender_item
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.cash_step_common_mobile_item
            }
            "SELECT" -> {//选择
                return R.layout.cash_step_common_select_item
            }
            else -> {//输入框
                return R.layout.cash_step_common_input_item
            }
        }
    }

    override fun setItemChildListener(helper: CashRootViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.selectLayout)//选择
        helper.setItemChildClickListener(R.id.imgContact)//选择联系人
        helper.setItemChildClickListener(R.id.textMobile)
    }

    override fun fillData(helper: CashRootViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val textTitle = helper.getTextView(R.id.textTitle)
        var showTitle = model.optString("title")
        if (CashRootConfigs.isSwahili()){
            showTitle = model.optString("title_sw")
        }
        textTitle.text = findKeywordColor(Color.parseColor("#FF4D3E"),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showCashRootStepItemSelectView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showCashRootStepItemContactMobileView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showCashRootStepItemSelectGenderView(helper,position,model)
            }
            else -> {//输入框
                showCashRootStepItemInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showCashRootStepItemInputView(helper: CashRootViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val editText = helper.getView<CustomEditText>(R.id.editText)
        var showHint = model.optString("hint")
        if (CashRootConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        editText.setHint(showHint)
        editText.setBackgroundResource(R.drawable.cash_radius_frame_dfe1e8_12)
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            if (selectItem != null) {
                showText = selectItem.optString("title")
            }
        }
        editText.setText(showText)
        editText.setInputFocusChangeListener { v, remark ->
            CashRootEventHelper.addCashRootRequestEventAction(String.format(CashRootEventType.FORM.CASHROOT_FORM_STEP_INPUT_XX,model.optString("paramName")),remark)
        }

        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }
        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择性别
     */
    private fun showCashRootStepItemSelectGenderView(helper: CashRootViewHolderHelper, position: Int, model: JSONObject){
        val txtGender1 = helper.getTextView(R.id.textGender1)
        txtGender1.setTextColor(Color.parseColor("#8C8EAF"))
        txtGender1.setBackgroundResource(R.drawable.cash_radius_frame_dfe1e8_12)

        val txtGender2 = helper.getTextView(R.id.textGender2)
        txtGender2.setTextColor(Color.parseColor("#8C8EAF"))
        txtGender2.setBackgroundResource(R.drawable.cash_radius_frame_dfe1e8_12)

        val values = model.optJSONArray("values")
        if (values != null){
            if (values.length() > 0){
                val item = values.optJSONObject(0)
                var showTitle = item.optString("title")
                if (CashRootConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                txtGender1.text = showTitle
            }
            if (values.length() > 1){
                val item = values.optJSONObject(1)
                var showTitle = item.optString("title")
                if (CashRootConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                txtGender2.text = showTitle
            }
        }

        //选中
        if (model.has("selectItem")){
            val selectValue = model.getJSONObject("selectItem")
            if (values != null){
                if (values.length() > 0){
                    val item = values.optJSONObject(0)
                    if (item.optString("title") == selectValue.optString("title")){
                        txtGender1.setTextColor(Color.parseColor("#435CFA"))
                        txtGender1.setBackgroundResource(R.drawable.cash_radius_frame_435cfa_12)
                    }
                }
                if (values.length() > 1){
                    val item = values.optJSONObject(1)
                    if (item.optString("title") == selectValue.optString("title")){
                        txtGender2.setTextColor(Color.parseColor("#435CFA"))
                        txtGender2.setBackgroundResource(R.drawable.cash_radius_frame_435cfa_12)
                    }
                }
            }
        }

        txtGender1.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(0)
                model.put("selectItem", item)
                CashRootEventHelper.addCashRootRequestEventAction(String.format(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }

        txtGender2.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(1)
                model.put("selectItem", item)
                CashRootEventHelper.addCashRootRequestEventAction(String.format(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }
    }

    /**
     * 选择类型
     */
    private fun showCashRootStepItemSelectView(helper: CashRootViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (CashRootConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val textValue = helper.getTextView(R.id.textValue)
        textValue.setHint(showHint)
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (CashRootConfigs.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            textValue.text = showTitle
        }

        val imgIcon = helper.getImageView(R.id.imgIcon)
        imgIcon.setImageResource(R.mipmap.cash_down_black)
        when(model.optString("action")){
            "SELECT" ->{//选择
                imgIcon.setImageResource(R.mipmap.cash_down_black)
            }
            "DATE_PICK" -> {//出生日期
                imgIcon.setImageResource(R.mipmap.cash_calendar)
            }
        }
    }

    /**
     * 联系电话
     */
    private fun showCashRootStepItemContactMobileView(helper: CashRootViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (CashRootConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val textMobile = helper.getTextView(R.id.textMobile)
        textMobile.setHint(showHint)
        val editMobile = helper.getView<EditText>(R.id.editMobile)
        editMobile.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            textMobile.text = showValue
            editMobile.setText(showValue)
        }
        editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editMobile.clearFocus()
                true
            }
            false
        }
        editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                CashRootEventHelper.addCashRootRequestEventAction(String.format(CashRootEventType.FORM.CASHROOT_FORM_STEP_INPUT_XX,model.optString("paramName")),editMobile.text.toString())
            }
        }
        editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isConfigAccount = SharedHelper.getCashRootSPBoolean(SharedHelper.CashRoot_SPKEY.CASHROOT_IS_CONFIG_ACCOUNT)
        if(isConfigAccount){//审核账号 - 允许输入或选择
            textMobile.visibility = View.GONE
            editMobile.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            textMobile.visibility = View.VISIBLE
            editMobile.visibility = View.GONE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}